#!/usr/bin/env python3
"""
镜像质量评估模块
"""

import logging
from datetime import datetime, timedelta
from typing import Dict, Tuple
from .core import GitSubmoduleManager

logger = logging.getLogger(__name__)

class MirrorEvaluator:
    """镜像质量评估器"""
    
    def __init__(self, git_manager: GitSubmoduleManager):
        self.git = git_manager
    
    def evaluate_mirror(self, original_url: str, mirror_url: str) -> Dict:
        """综合评估镜像质量"""
        logger.info(f"评估镜像: {original_url} → {mirror_url}")
        
        score = 0
        details = {
            "original_url": original_url,
            "mirror_url": mirror_url,
            "availability": False,
            "freshness_score": 0,
            "completeness_score": 0,
            "total_score": 0,
            "recommendation": "不推荐"
        }
        
        # 1. 可用性检查 (40分)
        availability = self.git.check_mirror_availability(mirror_url)
        details["availability"] = availability
        if availability:
            score += 40
            
            # 2. 新鲜度评估 (30分)
            freshness_score = self._evaluate_freshness(mirror_url)
            details["freshness_score"] = freshness_score
            score += freshness_score
            
            # 3. 完整性评估 (30分)
            completeness_score = self._evaluate_completeness(original_url, mirror_url)
            details["completeness_score"] = completeness_score
            score += completeness_score
        
        details["total_score"] = score
        
        # 生成推荐建议
        if score >= 80:
            details["recommendation"] = "强烈推荐"
        elif score >= 60:
            details["recommendation"] = "推荐使用"
        elif score >= 40:
            details["recommendation"] = "可用但有风险"
        else:
            details["recommendation"] = "不推荐"
        
        return details
    
    def _evaluate_freshness(self, mirror_url: str) -> int:
        """评估镜像新鲜度"""
        try:
            info = self.git.get_repo_info(mirror_url)
            if not info.get("last_commit"):
                return 0
            
            # 这里简化处理，实际应该解析提交时间
            # 假设能获取到提交信息就认为比较新
            return 25  # 给予中等分数
            
        except Exception as e:
            logger.warning(f"新鲜度评估失败: {e}")
            return 10
    
    def _evaluate_completeness(self, original_url: str, mirror_url: str) -> int:
        """评估镜像完整性"""
        try:
            original_info = self.git.get_repo_info(original_url)
            mirror_info = self.git.get_repo_info(mirror_url)
            
            original_tags = original_info.get("tags", 0)
            mirror_tags = mirror_info.get("tags", 0)
            
            if original_tags == 0:
                return 15  # 无法比较
            
            completeness_ratio = mirror_tags / original_tags
            
            if completeness_ratio >= 0.9:
                return 30
            elif completeness_ratio >= 0.7:
                return 20
            elif completeness_ratio >= 0.5:
                return 15
            else:
                return 10
                
        except Exception as e:
            logger.warning(f"完整性评估失败: {e}")
            return 10

